package com.example.community.controller;

import com.example.community.DTO.AddArticle;
import com.example.community.entity.article;
import com.example.community.service.AliFile;
import com.example.community.service.impl.AliFileImpl;
import com.example.community.service.impl.articleImpl;
import com.example.community.utils.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.util.List;

@RestController
@RequestMapping("/article")
@CrossOrigin("*")
public class articleController {
    @Autowired
    private com.example.community.service.impl.articleImpl articleImpl;
    @Autowired
    private com.example.community.service.impl.commentImpl commentImpl;

    @Autowired
    private AliFile aliFile;
    @GetMapping("/getAll")
    public Result<List<article>> getAllArticle(){
        List<article> all = articleImpl.getAll();
        return  Result.success(all, "success");
    }

    @GetMapping("/getOne/{id}")
    public Result<article> getOne(@PathVariable String id){
        article oneById = articleImpl.getOneById(id);
        return Result.success(oneById,"success");
    }

    @PostMapping("/addOne")
    public Result<String> addArticle(@RequestParam("file")MultipartFile file,@RequestPart("req") AddArticle addArticle) throws IOException {
        InputStream inputStream = file.getInputStream();
        String originalFilename = file.getOriginalFilename();
        String fileName = aliFile.upload(inputStream, originalFilename);
        addArticle.setCover_url(fileName);
        String articleId = articleImpl.addOne(addArticle);
        return Result.success(articleId,"新增文章成功");
    }

    @PostMapping("/update")
    public Result<article> updateArticle(@RequestBody article article){
        article article1 = articleImpl.updateOne(article);
        return Result.success(article1,"修改文章成功");
    }
//    删除文章之前先删除文章中的所有评论
    @GetMapping("/delete/{id}")
    public Result<String> delete(@PathVariable String id){
        commentImpl.deleteArticleAllComment(id);
        articleImpl.deleteOneArticle(id);
        return  Result.success("","成功删除ID为"+id+"的文章");
    }
}
